package projectmanagement.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.transaction.annotation.Transactional;

import projectmanagement.model.Person;
import projectmanagement.model.dao.PersonDao;

@Transactional
public class PersonDaoImpl implements PersonDao{
	
	protected final Log logger = LogFactory.getLog(getClass());
	
	private EntityManager em;
	
	@PersistenceContext
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

	public List<Person> getPersonList() {
        logger.info("Getting person list!");
        
        List<Person> resultList = em.createQuery("select p from Person p ORDER BY p.name").getResultList();
		return resultList;
	}
	
	public Person getPersonById(int id) {
		logger.info("Getting person by id: " + id);
		
		return em.find(Person.class, id);
	}
	
	public Person getPersonByUsername(String username) {
		logger.info("Getting person by username: " + username);
		try{
			return (Person) em.createQuery("from Person p where p.username = :username").setParameter("username", username).getSingleResult();
		}catch(NoResultException e){
			return null;
		}
	}
	
	public void save(Person person) { 
		if (person.getId() == 0) {
            // new
            em.persist(person);
        } else {
            // update
            em.merge(person);
        }
	}
	
	public void remove(int id) {
		Person person  = getPersonById(id);
	        if (person != null) {
	            em.remove(person);
	        } 
	}
}
